package uns.fit.gis.ui;

import java.util.Enumeration;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;

import uns.fit.gis.MapDrawer;
import uns.fit.gis.Util;
import uns.fit.gis.fileio.FileWrapper;
import uns.fit.gis.i18n.LocaleManager;
import uns.fit.gis.mapdrawer.LayerConfig;
import uns.fit.gis.mapdrawer.MapCanvas;
import uns.fit.gis.mapobj.SimpleLocation;

public class UserLocationList extends List implements CommandListener {
	private Command backCommand;
	private Command selectCommand;
	private Command deleteCommand;
	private Command deleteYesCommand;
	private Command deleteNoCommand;
	private Command convertToKmlCommand;
	private MapDrawer midlet;
	public UserLocationList(MapDrawer midlet) {
		super(LocaleManager.getMessage("title"), List.IMPLICIT);
		this.midlet = midlet;
		backCommand = new Command(LocaleManager.getMessage("back"), Command.BACK, 1);
		addCommand(backCommand);
		selectCommand = new Command(LocaleManager.getMessage("showmap"), Command.ITEM, 1);
		addCommand(selectCommand);
		convertToKmlCommand = new Command("KML", Command.ITEM, 1);
		deleteCommand = new Command(LocaleManager.getMessage("deletelocation"), Command.ITEM, 1);
		addCommand(deleteCommand);
		deleteYesCommand = new Command(LocaleManager.getMessage("yes"), Command.OK, 1);
		deleteNoCommand = new Command(LocaleManager.getMessage("no"), Command.CANCEL, 1);
		addCommand(convertToKmlCommand);
		setCommandListener(this);
		
		addUserLocations();
	}
	private void addUserLocations() {
			Enumeration locationEnum = MapCanvas.userLocations.elements();
	        while (locationEnum.hasMoreElements() == true) {
	            SimpleLocation location = (SimpleLocation)locationEnum.nextElement();
	            StringBuffer strBuf = new StringBuffer();
	            strBuf.append(Util.decodeCharacters(location.getName())).
	            	append(Util.getLatitude(location.getY())).
	            	append(Util.getLongitude(location.getX()));
	            append(strBuf.toString(), null);
	        }
	}
	public void commandAction(Command command, Displayable displayable) {
		if(command == backCommand) {
			midlet.showMapCanvas();
		}
		else if(command == selectCommand) {
			if(getSelectedIndex() != -1) {
				SimpleLocation location = (SimpleLocation)MapCanvas.userLocations.elementAt(getSelectedIndex());
				Util.centerScreen(location.getX(), location.getY());
				midlet.showMapCanvas();
			}
		}
		else if(command == convertToKmlCommand) {
			if(getSelectedIndex() != -1) {
				final String kml = convertToKml(getString(getSelectedIndex()), (SimpleLocation)MapCanvas.userLocations.elementAt(getSelectedIndex()));
				new Thread() {
					public void run() {
						FileWrapper.save(kml.getBytes(), midlet.getSettings().getStorageFolder() + getString(getSelectedIndex()).replace(' ', '_').replace(':', '_') + ".kml");
					}
				}.start();
			}
		}
		else if(command == deleteCommand) {
			if(getSelectedIndex() != -1) {
				Alert alert = new Alert(LocaleManager.getMessage("title"), LocaleManager.getMessage("deleteconfirm"), null, AlertType.CONFIRMATION );
				alert.addCommand(deleteYesCommand);
				alert.addCommand(deleteNoCommand);
				alert.setCommandListener(this);
				MapDrawer.showAlert(alert);
			}
		}
		else if(command == deleteYesCommand) {
			System.out.println("Deleted");
			int selected = getSelectedIndex();
			delete(selected);
			SimpleLocation location = (SimpleLocation)MapCanvas.userLocations.elementAt(selected);
			if(location.getType() == LayerConfig.LAYER_CONSTRUCTIONSITE) {
				int segmentId = Util.findClosestSegment2(location.getX(), location.getY());
				if(segmentId != -1)
					MapCanvas.constructionSiteSegmentIds.removeElement(new Integer(segmentId));
			}
			MapCanvas.userLocations.removeElementAt(selected);
			MapDrawer.getMidlet().show(this);
		}
		else if(command == deleteNoCommand) {
			System.out.println("Cancel");
			MapDrawer.getMidlet().show(this);
		}
	}
	
	private String convertToKml(String name, SimpleLocation location) {
		StringBuffer placeString = new StringBuffer();
        RouteList.addHeader(placeString, name);
        RouteList.closeTrack(placeString);
        placeString.append(generatePlaceMarkData(location));
        RouteList.addFooter(placeString);
        return placeString.toString();
	}
	
	private StringBuffer generatePlaceMarkData(SimpleLocation location) {
        StringBuffer placeString = new StringBuffer();
        placeString.append("<Folder>\r\n");
        placeString.append("<name>Places</name>\r\n");
        placeString.append("<Placemark>\r\n");
        placeString.append("<name>MapDrawer</name>\r\n");
        placeString.append("<Point><coordinates>\r\n");
        placeString.append(formatDegrees(Util.getLongitude(location.getX()))).append(",")
                    .append(formatDegrees(Util.getLatitude((short)location.getY()))).append(",0\r\n");
        placeString.append("</coordinates></Point>\r\n");
        placeString.append("</Placemark>\r\n");
        placeString.append("</Folder>\r\n");
        return placeString;
    }
	
	private String formatDegrees(double degrees) {
        return String.valueOf(((int) (degrees * 1000000)) / 1000000.0);
    }
}
